package com.baofu.paycore.service.validate.impl.consume;

import com.baofu.paycore.common.enums.RedisKeyEnum;
import com.baofu.paycore.common.exception.ServiceErrorCode;
import com.baofu.paycore.manager.cache.RedisLockManager;
import com.baofu.paycore.manager.model.PayBaseBO;
import com.baofu.paycore.manager.storer.OrderRepository;
import com.baofu.paycore.service.facade.enums.PayCoreErrorCode;
import com.baofu.paycore.service.facade.enums.PayStatusEnums;
import com.baofu.paycore.service.facade.model.PayBaseResDTO;
import com.baofu.paycore.service.facade.model.PayConfirmReqDTO;
import com.google.common.base.Objects;
import com.system.commons.result.Result;
import com.system.commons.utils.BeanCopyUtil;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

/**
 * 消费确认校验器
 *
 * User: XiaChen
 * Date: 17-04-06
 */
@Slf4j
@Service
public class ConsumeConfirmValidate{

    /**
     * redis锁服务
     */
    @Autowired
    private RedisLockManager lockManager;


    /**
     * 锁定支付订单
     *
     * @param t     被校验对象
     */
    public boolean lock(PayConfirmReqDTO t){
        return lockManager.lock(RedisKeyEnum.PAY_SERVICE,t.getRequestBizNo(),t.getRequestOrderNo());
    }

    /**
     * 释放订单锁
     *
     * @param t     被校验对象
     */
    public void release(PayConfirmReqDTO t,boolean flag){
        if(flag){
            lockManager.release(RedisKeyEnum.PAY_SERVICE,t.getRequestBizNo(),t.getRequestOrderNo());
        }
    }

    /**
     * 订单状态校验
     *
     * @param t     被校验对象
     */
    public <E> Result<E> validateOrder(PayConfirmReqDTO t, OrderRepository orderRepository, Class<E> clazz){
        PayBaseBO order = orderRepository.checkIdempotent(t.getRequestBizNo(),t.getRequestOrderNo(),t.getRequestSystem());
        if(order == null){
            log.warn("订单不存在:{},{}",t.getRequestBizNo(),t.getRequestOrderNo());
            return new Result<>(BeanCopyUtil.objConvert(new PayBaseResDTO(PayCoreErrorCode.ORDER_IS_NOT_EXISTED.getErrorCode(),
                    PayCoreErrorCode.ORDER_IS_NOT_EXISTED.getErrorDesc(), order.getStatus()),clazz));
        }

        if(Objects.equal(PayStatusEnums.SUCCESS.getCode(),order.getStatus())){
            log.warn("原订单状态交易已经成功 {}",order.getStatus());
            return new Result<>(BeanCopyUtil.objConvert(order, clazz));
        }
        t.setPayNo(order.getPayNo());
        return null;
    }


}
